package test.boid.vo;

import java.nio.FloatBuffer;
import java.util.*;

import com.jme.math.Vector3f;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Controller;
import com.jme.scene.Line;
import com.jme.scene.Node;
import com.jme.scene.Line.Mode;
import com.jme.scene.Spatial.LightCombineMode;
import com.jme.scene.state.LightState;
import com.jme.system.DisplaySystem;
import com.jme.util.geom.BufferUtils;

public class SphereTraceVO extends SphereVO {
	static final int traceLength = 50;
	Line lineTrace;
	Vector3f trace[];

	public SphereTraceVO(HashMap<String, Object> initVector) {
		super(initVector);

		trace = new Vector3f[traceLength];
		// for (int i = 0; i < traceLength; i++) {
		// trace[i] = new Vector3f(getRenderNode().getLocalTranslation());
		// }
		lineTrace = new Line("", new Vector3f[traceLength], null, null, null);
		lineTrace.setSolidColor(new ColorRGBA(1, 1, 1, 1));
		lineTrace.setLightCombineMode(LightCombineMode.Off);
		lineTrace.setMode(Mode.Connected);
		// lineTrace.setRandomColors();
		LightState ls = DisplaySystem.getDisplaySystem().getRenderer()
				.createLightState();
		ls.setEnabled(false);
		lineTrace.setRenderState(ls);
		lineTrace.updateRenderState();

		getRenderNode().attachChild(lineTrace);
	}

	private void updateTrace() {
		Node renderNode = getRenderNode();
		// if (!renderNode.getLocalTranslation().equals(trace[0])) {
		if (trace[0] == null
				|| renderNode.getLocalTranslation().subtract(trace[0]).length() > 3) {
			for (int i = trace.length - 1; i >= 1; i--) {
				if (trace[i - 1] == null)
					trace[i - 1] = new Vector3f(renderNode
							.getLocalTranslation());
				trace[i] = trace[i - 1];
			}
			trace[0] = new Vector3f(renderNode.getLocalTranslation());
		}
		Vector3f objSpace[] = new Vector3f[traceLength];
		for (int i = 0; i < traceLength; i++) {
			objSpace[i] = new Vector3f();
			renderNode.worldToLocal(trace[i], objSpace[i]);
			// System.out.println("I:"+i+"->"+objSpace[i]);
		}

		FloatBuffer buffer = BufferUtils.createFloatBuffer(objSpace);

		lineTrace.setVertexBuffer(buffer);
	}

	@Override
	public void renderUpdate(float fpt) {
		updateTrace();
		lineTrace.updateGeometricState(0, true);
		lineTrace.updateModelBound();
	}
}
